package com.yc.mvc.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.InputStream;
import java.io.PrintWriter;

// @Controller 表示给类每个方法返回的是视图( jsp , html)
@Controller
@RequestMapping("param")
public class ParamController {

    @GetMapping("hello")
    @ResponseBody // 表示该方法返回 json 数据
    public String hello (String name){
        return "hello " + name;
    }

    @GetMapping("add")
    @ResponseBody // 表示该方法返回 json 数据
    public int add (
            @RequestParam(name="x",defaultValue = "5") int a,
            @RequestParam(name="y",defaultValue = "3") int b,
            boolean c){
        return c ? a + b : a - b;
    }

    @GetMapping("reg")
    @ResponseBody
    public User reg( User user){
        return user;
    }

    public void servlet(
            HttpServletRequest request,
            HttpServletResponse response,
            HttpSession session,
            InputStream in,
            PrintWriter out){
        response.setContentType("text/html");
        out.append("<ul>")
                .append("<li>").append(request.toString())
                .append("<li>").append(response.toString())
                .append("<li>").append(session.toString())
                .append("<li>").append(in.toString())
                .append("<li>").append(out.toString())
                .append("</ul>");

    }

    // 地址参数不是请求参数
    // 127.0.0.1/xxx/ppp/aaa?    ppp 地址参数
    @GetMapping("user/{id}")    // user/123
    @ResponseBody
    // restful 请求风格 method 标记业务类型 delete put
    public String pathVariable(@PathVariable int id){
        return id + "";
    }

    // 获取头域参数
    @GetMapping
    @ResponseBody
    public String header1(
            @RequestHeader String Host,
            @RequestHeader(value = "Accept", required = false) String accept,
            @RequestHeader(value = "Cookie", required = false) String cookie){

    return Host + "<br>" + accept + "<br>" + cookie + "<br>" ;
    }

    @GetMapping("cookie")
    @ResponseBody
    public String cookie(
            @CookieValue(value = "name", required = false) String name){
        return "cookie: " + name;
    }
}
